import 'package:speech_to_text/speech_to_text.dart' as stt;
import 'package:logging/logging.dart';

class SpeechToTextService {
  final stt.SpeechToText _speechToText = stt.SpeechToText();
  bool _isInitialized = false;
  final _logger = Logger('SpeechToTextService');

  Future<bool> initialize() async {
    if (!_isInitialized) {
      try {
        _isInitialized = await _speechToText.initialize(
          onError: (errorNotification) => _logger.warning(
              'Speech recognition error: ${errorNotification.errorMsg}'),
          onStatus: (status) =>
              _logger.info('Speech recognition status: $status'),
          debugLogging: true,
        );

        if (_isInitialized) {
          // 检查语音识别服务是否可用
          final hasPermission = await _speechToText.hasPermission;
          if (!hasPermission) {
            return false; // 如果没有权限，返回初始化失败
          }
          return true;
        }
      } catch (e) {
        _logger.severe('Speech recognition initialization error: $e');
        _isInitialized = false;
        return false;
      }
    }
    return _isInitialized;
  }

  Future<void> startListening(void Function(String) onResult) async {
    try {
      if (!_isInitialized) {
        final initialized = await initialize();
        if (!initialized) {
          throw Exception('语音识别初始化失败');
        }
      }

      if (!_speechToText.isAvailable) {
        throw Exception('语音识别不可用');
      }

      // 确保先停止当前录音
      if (_speechToText.isListening) {
        await stopListening();
        // 添加短暂延迟确保完全停止
        await Future<void>.delayed(const Duration(milliseconds: 200));
      }

      await _speechToText.listen(
        onResult: (result) => onResult(result.recognizedWords),
        listenOptions: stt.SpeechListenOptions(
          listenMode: stt.ListenMode.dictation,
          cancelOnError: true,
          partialResults: true,
        ),
      );
    } catch (e) {
      _logger.severe('Start listening error: $e');
      throw Exception('开始语音识别失败: $e');
    }
  }

  Future<void> stopListening() async {
    try {
      if (_speechToText.isListening) {
        await _speechToText.stop();
      }
    } catch (e) {
      _logger.severe('Stop listening error: $e');
    }
  }

  bool get isListening => _speechToText.isListening;
}
